<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Log;
use app\index\model\vo_video_manage;

class Api extends Controller
{
    public function index()
    {
        echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阿拉贡app</title>
    阿拉贡app
</head>
<body>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?bf36a1bc063e6437a30fb80573711ea5";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
</body>
</html>';
    }

    public function h5_index()
    {
        $classId = input('classId');

        //默认使用db1
        session_init();

        is_login(11); //渠道登录统计

        $menu = [
            567066 => '腿精',
            568179 => '鬼畜',
            567070 => '开箱',
            567067 => '熟肉',
        ];

        $this->assign('menu', $menu);
        $this->assign('classId', $classId);
        return view("");
    }

    public function h5_search()
    {
        if (IS_POST) {
            $keyword = input('keyword');
            if ($keyword) {
                $map = [];
                $map['fileName'] = ['like', "%$keyword%"];
                $map['isLine'] = ['=', 0];
                $map['classId'] = ['in', [567066, 568179, 567070, 567067]];
            } else {
                return json(['code' => 200, 'data' => '']);
            }

            $vo_video_manage = new vo_video_manage();
            $data = $vo_video_manage->where($map)->select();

            $new_data = [];
            foreach ($data as $v) {
                $fileUrl = url_key($v['fileUrl']);
                $new_data[] = [
                    'fileId' => $v['fileId'],
                    'fileUrl' => $fileUrl,
                    'fileName' => $v['fileName'],
                    'pic' => $v['pic'],
                    'play' => $v['play'],
                    'duration' => $v['duration'],
                    'cid' => $v['classId'],
                    'love' => $v['love']
                ];
            }

            return json(['code' => 200, 'data' => $new_data]);
        }

        $KeySearch = ["女优", "性感舞蹈", "内衣开箱", "大长腿", "游戏", "街拍"];

        //推荐
        $data_t = Db::table('vo_video_manage')
            ->where('classId', 'in', [567066, 568179])
            ->order('createTime desc')
            ->limit(2)
            ->select();

        $this->assign('KeySearch', $KeySearch);
        $this->assign('data_t', $data_t);
        return view("");
    }

    public function h5_user()
    {
        $user_token = cookie('user_token');
        $user = Db::table('vo_app_user')->where(['token' => $user_token])->find();
        if ($user) {
            if (strtotime($user['vip_exp_date']) > time()) {
                $user['vip'] = true;
            } else {
                $user['vip'] = false;
            }

            //没有过期的订单中 选择最高的爵位
            if (strtotime($user['nobility_exp_date']) > time()) {
                $orders = Db::table('vo_app_order')
                    ->where(['memberId' => $user['memberId'], 'state' => 1])
                    ->order('createTime desc')
                    ->select();

                $arr = [];
                foreach ($orders as $v) {
                    $price_type = $v['price_type'];
                    if (strpos($price_type, '100') === 0) {
                        if (strtotime($v['vip_exp_date']) > time()) {
                            $id = str_replace('100', "", $price_type);
                            $arr[] = $id;
                        }
                    }
                }

                if ($arr) {
                    $nobility = Db::table('vo_nobility')->where(['state' => 0, 'id' => max($arr)])->find();
                    if ($nobility) {
                        $user['nobility'] = $nobility;
                    }
                }
            }

            //加入签到显示
            $config = config('points_config')['pd_sign'];
            $points_type = $config['type'];

            $res = Db::table('vo_points_log')
                ->where(['points_type' => $points_type, 'app_user_id' => $user['id']])
                ->whereTime('log_add_time', 'today')
                ->find();

            $res ? $user['sign'] = true : $user['sign'] = false;
        } else {
            cookie('user_token', null);
            $user['vip'] = false;
        }

        $ad = Db::table('vo_ad')->where(['type' => 'aragon_banner', 'state' => 1])->cache(60)->select();

        $this->assign('ad', $ad);
        $this->assign('user', $user);
        return view("");
    }

    public function kv_index()
    {
        if (IS_POST) {
            $pageNum = input('pageNum', 1);
            $pageSize = input('pageSize', 10);

            $kv_list = Db::table('vo_video_manage')
                ->field('id,fileId,fileUrl,pic,love')
                ->where(['classId' => 596666, 'isLine' => 0])
                ->order('updateTime desc')
                ->page($pageNum, $pageSize)
                ->select();

            $totalSize = Db::table('vo_video_manage')
                ->where(['classId' => 596666, 'isLine' => 0])
                ->order('updateTime desc')
                ->count();

            $redis = redis_init();
            foreach ($kv_list as $key => $v) {
                //fileUrl生成url
                $fileUrl = $redis->hGet('vod_url_cache', $v['fileId']);
                if (!$fileUrl) {
                    $fileUrl = url_key($v['fileUrl']);
                }

                $kv_list[$key]['fileUrl'] = $fileUrl;
            }

            ob_start('ob_gzhandler');

            return json(['code' => 200, 'data' => $kv_list, 'totalSize' => $totalSize]);
        }

        return view();
    }

    public function get_next_vod()
    {
        $id = input('id');
        $sort = input('sort');
        if ($sort == 'before') { //上一条
            $one = Db::table('vo_video_manage')
                ->field('id,fileId,fileUrl,love')
                ->where(['classId' => 596666, 'isLine' => 0, 'id' => ['<', $id]])
                ->order('id desc')
                ->find();
        } else { //下一条
            $one = Db::table('vo_video_manage')
                ->field('id,fileId,fileUrl,love')
                ->where(['classId' => 596666, 'isLine' => 0, 'id' => ['>', $id]])
                ->order('id asc')
                ->find();
        }

        if ($one) {
            $redis = redis_init();
            $fileUrl = $redis->hGet('vod_url_cache', $one['fileId']);

            if ($fileUrl) {
                $one['fileUrl'] = $fileUrl;
            } else {
                $one['fileUrl'] = url_key($one['fileUrl']);
            }

            return json(['code' => 200, 'data' => $one]);
        } else {
            return json(['code' => 500]);
        }
    }

    //////////////////接口//////////////////

    public function get_h5_video()
    {
        $classId = input('classId');
        $page = input('page', 1);
        $limit = input('l', 0);

        $where = [];

        if ($classId) {
            //显示分类视频
            $where['isLine'] = 0;
            $where['classId'] = $classId;

            $vo_video_manage = new vo_video_manage();
            $data = $vo_video_manage->get_videos_h5($where, $limit, $page);
        } else {
            //显示推荐视频(热力值大于100)
            if ($page == 1) {
                $where['isLine'] = 0;
                $where['hotNum'] = ['>=', 100];
                $subQuery = Db::table('vo_video_manage')->where($where)
                    ->where('classId', 'in', [567066, 568179, 567067, 567069])
                    ->orderRaw('rand()')->limit(0, 20)->buildSql();
                $data = Db::table($subQuery . ' a')->order('a.hotNum', 'desc')->select();
            } else {
                $data = [];
            }
        }

        $new_data = [];
        foreach ($data as $v) {
            if ($classId) {
                $cid = $classId;
            } else {
                $cid = $v['classId'];
            }

            if ($v['isFree'] == 1) {
                $fileUrl = url_key($v['fileUrl'], $v['dur_free']);
            } else {
                $fileUrl = url_key($v['fileUrl']);
            }

            $new_data[] = [
                'fileId' => $v['fileId'],
                'fileUrl' => $fileUrl,
                'fileName' => $v['fileName'],
                'pic' => $v['pic'],
                'play' => $v['play'],
                'duration' => $v['duration'],
                'cid' => $cid,
                'isFree' => $v['isFree'],
                'love' => $v['love']
            ];
        }

        return json(['code' => 200, 'data' => $new_data]);
    }

    public function get_kv_wall()
    {
        $page = input('page', 1);
        $limit = 20;
        $start = ($page - 1) * $limit;

        $data = Db::table('vo_video_manage')
            ->where(['classId' => 596666, 'isLine' => 0])
            ->order('updateTime desc')
            ->limit($start, $limit)
            ->select();

        $redis = redis_init();

        $new_data = [];
        foreach ($data as $v) {
            $fileUrl = $redis->hGet('vod_url_cache', $v['fileId']);
            if (!$fileUrl) {
                $fileUrl = url_key($v['fileUrl']);
            }

            $new_data[] = [
                'fileId' => $v['fileId'],
                'fileUrl' => $fileUrl,
                'fileName' => $v['fileName'],
                'pic' => $v['pic'],
                'play' => $v['play'],
                'duration' => $v['duration'],
                'love' => $v['love'],
            ];
        }

        ob_start('ob_gzhandler');
        return json(['code' => 200, 'data' => $new_data]);
    }

    public function vod_zan()
    {
        $fid = input('fid');
        $type = input('type');
        if ((int)$type === 1) {
            Db::table('vo_video_manage')->where('fileId', $fid)->setInc('love');
        } else {
            Db::table('vo_video_manage')->where('fileId', $fid)->setDec('love');
        }

        return json(['code' => 200, 'msg' => 'sucess']);
    }

    public function launch_page()
    {
        $redis = redis_init();
        $ad_launch_page_img = json_decode($redis->get('ad_launch_page_img'), true);
        $ad_launch_page_vod = json_decode($redis->get('ad_launch_page_vod'), true);

        if ($ad_launch_page_img) {
            return json(['code' => 200, 'type' => 0, 'data' => ['t' => (int)$ad_launch_page_img['path'], 'src' => $ad_launch_page_img['link']]]);
        }

        if ($ad_launch_page_vod) {

        }

        return json(['code' => 500]);
    }

    public function launch_page_set()
    {
        if (IS_POST) {
            $path = input('path');
            $link = input('link');

            $redis = redis_init();
            $redis->set('ad_launch_page_img', json_encode(['path' => $path, 'link' => $link]));

            echo '设置成功！';
            exit();
        }

        echo <<<EOT
<html>
<head>
<meta charset="utf-8">
<title>设置启动页</title>
</head>
<body>
<h1>设置启动页</h1>
<form action="/launch_page_set" method="post" enctype="multipart/form-data" >
    倒计时：<input type="number" step=1 name="path"> <br>
    图片链接：<input type="text" name="link">
    <input type="submit" name="submit" value="提交">
</form>
</body>
</html>
EOT;
    }

    public function video_stats_index()
    {
        $type = input('type');
        $channel = input('channel');
        $current_vid = input('current_vid');
        $currentTime = floor(input('currentTime')); //单位秒
        $exposure = input('exp', 0); //视频曝光次数(播放大于70%)

        if (!$current_vid || !$channel || !$type) {
            return 'error';
        }

        $now = date("Y-m-d");

        //单独渠道播放量和播放时长统计
        $redis = redis_init();
        $redis->hIncrBy('channel:' . $now . '.vod_val', $channel, 1);
        $redis->hIncrBy('channel:' . $now . '.vod_time', $channel, $currentTime);

        //用户视频日志插入(redis出栈入栈)
        //单人观看记录添加
        $user_sess = "";
        if (cookie('PHPSESSID')) {
            $user_sess = cookie('PHPSESSID');
        }

        $data = [
            'vod' => $current_vid,
            'vod_time' => round(input('currentTime'), 2),
            'channel' => $channel,
            'user_sess' => $user_sess,
            'createTime' => date('Y-m-d H:i:s', time()),
            'exp' => (int)$exposure
        ];

        //单视频统计(没有就新增，有就更改)
        if ($type == "local") {
            $redis->hIncrBy('local:' . $now . '.play', $current_vid, 1);
            $redis->hIncrBy('local:' . $now . '.playedTime', $current_vid, $currentTime);
//            $this->redis->rpush('log_queue_local', json_encode($data));
        } else {
            $redis->hIncrBy('vod_manage_play', $current_vid, 1);
            $redis->hIncrBy('vod_manage_playedTime', $current_vid, $currentTime);
            $redis->rpush('log_queue_inline', json_encode($data));
        }

        return json(['code' => 200]);
    }

    //////////////////分享//////////////////

    public function share_page1()
    {
        $fid = input('fid');
        if (!$fid) {
            return 'error';
        }

        $first = Db::table('vo_video_manage')->where(['fileId' => $fid])->find();
        $first['fileUrl'] = url_key($first['fileUrl']);

        $video_sort = [567066, 568179, 567070, 567067, 567069];
        foreach ($video_sort as $key => $value) {
            if ($value == $first['classId']) {
                unset($video_sort[$key]);
            }
        }

        $two = Db::table('vo_video_manage')
            ->where(['isLine' => 0])
            ->where('classId', 'in', $video_sort)
            ->orderRaw('rand()')->limit(6)->select();

        $three = Db::table('vo_video_manage')
            ->where(['isLine' => 0, 'classId' => $first['classId']])
            ->orderRaw('rand()')->limit(6)->select();

        $this->assign('first', $first);
        $this->assign('two', $two);
        $this->assign('three', $three);
        return view();
    }

    public function share_page2()
    {
        $fid = input('fid');
        if (!$fid) {
            return 'error';
        }

        $first = Db::table('vo_video_manage')->where(['fileId' => $fid])->find();
        $two = Db::table('vo_video_manage')
            ->where(['isLine' => 0, 'classId' => 596666])
            ->orderRaw('rand()')->limit(6)->select();

        $this->assign('first', $first);
        $this->assign('two', $two);
        return view();
    }

    public function share_ali()
    {
        return view();
    }

    public function download()
    {
        return view();
    }

    public function version()
    {
        $config = config('_download');
        return json(['link' => $config['url'], 'verName' => $config['verName'], 'verCode' => $config['verCode']]);
    }

    public function agreement()
    {
        return view();
    }

    public function policy()
    {
        return view();
    }

    public function settings()
    {
        $config = config('_download');
        $version = ['link' => $config['url'], 'verName' => $config['verName'], 'verCode' => $config['verCode']];

        $this->assign('version', json_encode($version));
        return view();
    }

    public function h5_vip_video()
    {
        //vip播放页面
        //登录校验
        $user_token = cookie('user_token');
        $user = Db::table('vo_app_user')->where(['token' => $user_token])->find();
        if (!$user) {
            cookie('user_token', null);
            return view("h5_vip_video_default");
        } else {
            if (strtotime($user['vip_exp_date']) >= time()) {
                return view("");
            } else {
                //$this->redirect('/buy_vod_vip');
                $map['state'] = ['=', 0];
                $map['type'] = ['like', "%app_%"];

                $list = Db::table('vo_price')->where($map)->select();
                $nobility = Db::table('vo_config')->field('value')->where(['key' => 'nobility'])->find();
                $vip_str = Db::table('vo_config')->field('value')->where(['key' => 'vip_str'])->find();

                !$nobility && $nobility = 0;
                !$vip_str && $vip_str = "";

                $this->assign('user', $user);
                $this->assign('list', $list);
                $this->assign('show', false);
                $this->assign('vip_str', $vip_str['value']);
                $this->assign('nobility', $nobility['value']);
                return view("index/buy_vod_vip");
            }
        }
    }

    public function pw_page()
    {
        if (IS_POST) {
            $pageNum = input('pageNum', 1);
            $pageSize = input('pageSize', 10);

            $list = Db::table('pw_girl')
                ->field('id,girl_name,girl_des,girl_tag,girl_look,add_time,girl_img,girl_vod,province,city')
                ->where(['is_del' => 0, 'status' => 1])
                ->order('add_time desc')
                ->page($pageNum, $pageSize)
                ->select();

            $totalSize = Db::table('pw_girl')
                ->where(['is_del' => 0, 'status' => 1])
                ->order('girl_look desc')
                ->count();

            $list = $this->tagName($list);
            return json(['code' => 200, 'data' => $list, 'totalSize' => $totalSize]);
        }

        return view("");
    }

    //获取girl标签
    public function pw_girl_tag()
    {
        $tag = Db::table('pw_girl_tag')->field('tag_id,tag_name')->where(['is_del' => 0])->select();
        return json(['code' => 200, 'data' => $tag]);
    }

    //获取girl2标签
    public function pw_girl_tag2()
    {
        $tag1 = input('tag1');
        $where['is_del'] = 0;
        $where['tag_id'] = array('neq', $tag1);
        $tag = Db::table('pw_girl_tag')->field('tag_id,tag_name')->where($where)->select();
        return json(['code' => 200, 'data' => $tag]);
    }

    public function tagName($list)
    {
        $tagTmp = [];
        $tag = Db::table('pw_girl_tag')->where(['is_del' => 0])->select();
        foreach ($tag as $t) {
            $tagTmp[$t['tag_id']] = $t['tag_name'];
        }

        foreach ($list as $key => $val) {
            $tmp = [];
            $arr = explode(',', $val['girl_tag']);
            foreach ($arr as $v) {
                if (isset($tagTmp[$v])) {
                    $tmp[] = $tagTmp[$v];
                }
            }
            $list[$key]['girl_tag'] = $tmp;
        }

        return $list;
    }

    public function pw_play()
    {
        $fid = input('fid');
        $vo_video_manage = new vo_video_manage();
        $data = $vo_video_manage->field('fileUrl')->where(['isLine' => 0, 'fileId' => $fid])->find();
        if (!$data) {
            return json(['code' => 500]);
        }

        $fileUrl = url_key($data['fileUrl']);
        $this->assign('fileUrl', $fileUrl);
        return view("");
    }

    public function pw_page_share()
    {
        if (IS_POST) {
            $pageNum = input('pageNum', 1);
            $pageSize = input('pageSize', 10);

            $list = Db::table('pw_girl')
                ->field('id,girl_name,girl_des,girl_tag,girl_look,add_time,girl_img,girl_vod,province,city')
                ->where(['is_del' => 0, 'status' => 1])
                ->order('add_time desc')
                ->page($pageNum, $pageSize)
                ->select();

            $totalSize = Db::table('pw_girl')
                ->where(['is_del' => 0, 'status' => 1])
                ->order('girl_look desc')
                ->count();

            $list = $this->tagName($list);
            return json(['code' => 200, 'data' => $list, 'totalSize' => $totalSize]);
        }

        return view("");
    }

    //异步获取腾讯云封面截取
    public function pw_video()
    {
        $fileId = input('fileId');
        $conf = config('tencent.wo');
        $SecretId = $conf['TencentCloudSecretId'];
        $SecretKey = $conf['TencentCloudSecretKey'];

        $Nonce = rand(111111, 999999);
        $time = time();
        $str = 'Action=GetVideoInfo&Nonce=' . $Nonce . '&Region=sh&SecretId=' . $SecretId . '&Timestamp=' . $time . '&fileId=' . $fileId;
        $srcStr = 'GETvod.api.qcloud.com/v2/index.php?' . $str;
        $signStr = base64_encode(hash_hmac('sha1', $srcStr, $SecretKey, true));
        $signStr = urlencode($signStr);

        $str = 'https://vod.api.qcloud.com/v2/index.php?' . $str . '&Signature=' . $signStr;

        $response = $this->curl_file_get_contents($str);

        return json(json_decode($response));

    }

    function curl_file_get_contents($durl)
    {
        // header传送格式
        $headers = array();
        // 初始化
        $curl = curl_init();
        // 设置url路径
        curl_setopt($curl, CURLOPT_URL, $durl);
        // 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        // 添加头信息
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        // CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // 不验证SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 执行
        $data = curl_exec($curl);
        // 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
        // 关闭连接
        curl_close($curl);
        // 返回数据
        return $data;
    }
}
